<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const loading = ref(false)
const schedules = ref([])
const doctorSchedules = ref([])
const timeSlots = ref([])
const currentDate = ref(new Date())

// 创建axios实例
const api = axios.create({
  baseURL: 'http://127.0.0.1:8000',
  timeout: 10000
})

// 添加请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
api.interceptors.response.use(
  response => {
    if (response.data.code === 401) {
      handleLogout()
      return Promise.reject(new Error('用户未登录或登录已过期'))
    }
    return response
  },
  error => {
    if (error.response && error.response.status === 401) {
      handleLogout()
    }
    return Promise.reject(error)
  }
)

// 处理登出
const handleLogout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('userid')
  localStorage.removeItem('permissions')
  localStorage.removeItem('userInfo')
  ElMessage.error('用户未登录或登录已过期，请重新登录')
  router.push('/')
}

// 获取基础排班时间段
const fetchSchedules = async () => {
  try {
    const response = await api.get('/background/schedules/')
    console.log('Schedules response:', response)
    if (response.data.code === 200) {
      schedules.value = response.data.data
    } else {
      ElMessage.error(response.data.message || '获取排班时间段失败')
    }
  } catch (error) {
    console.error('Schedules error:', error)
    ElMessage.error('获取排班时间段失败：' + (error.response?.data?.message || error.message))
  }
}

// 获取医生排班信息
const fetchDoctorSchedules = async () => {
  try {
    const response = await api.get('/background/doctor-schedules/', {
      params: {
        date: formatDate(currentDate.value)
      }
    })
    console.log('Doctor schedules response:', response)
    if (response.data.code === 200) {
      doctorSchedules.value = response.data.data
    } else {
      ElMessage.error(response.data.message || '获取医生排班信息失败')
    }
  } catch (error) {
    console.error('Doctor schedules error:', error)
    ElMessage.error('获取医生排班信息失败：' + (error.response?.data?.message || error.message))
  }
}

// 获取时间段预约信息
const fetchTimeSlots = async () => {
  loading.value = true
  try {
    const response = await api.get('/background/time-slots/', {
      params: {
        date: formatDate(currentDate.value)
      }
    })
    console.log('Time slots response:', response)
    if (response.data.code === 200) {
      timeSlots.value = response.data.data
    } else {
      ElMessage.error(response.data.message || '获取时间段预约信息失败')
    }
  } catch (error) {
    console.error('Time slots error:', error)
    ElMessage.error('获取时间段预约信息失败：' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return year + '-' + month + '-' + day
}

// 处理日期变化
const handleDateChange = (date) => {
  currentDate.value = date
  fetchDoctorSchedules()
  fetchTimeSlots()
}

// 获取时间段的预约信息
const getTimeSlotInfo = (scheduleId, doctorId) => {
  return timeSlots.value.find(slot => 
    slot.schedule_id === scheduleId && 
    slot.doctor_id === doctorId
  ) || null
}

// 获取医生的排班信息
const getDoctorSchedule = (scheduleId, doctorId) => {
  return doctorSchedules.value.find(schedule => 
    schedule.schedule_id === scheduleId && 
    schedule.doctor_id === doctorId
  ) || null
}

onMounted(() => {
  // 检查token是否存在
  const token = localStorage.getItem('token')
  console.log('Current token:', token)
  
  if (!token) {
    handleLogout()
    return
  }
  
  fetchSchedules()
  fetchDoctorSchedules()
  fetchTimeSlots()
})
</script>

<template>
  <div class="schedule-container">
    <div class="page-header">
      <h2>医生排班管理</h2>
      <el-date-picker
        v-model="currentDate"
        type="date"
        placeholder="选择日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        @change="handleDateChange"
      />
    </div>

    <el-card v-loading="loading">
      <el-table
        :data="schedules"
        border
        style="width: 100%"
      >
        <el-table-column
          prop="period"
          label="时间段"
          width="180"
        >
          <template #default="{ row }">
            {{ row.start_time }} - {{ row.end_time }}
          </template>
        </el-table-column>

        <el-table-column
          v-for="doctor in doctorSchedules"
          :key="doctor.doctor_id"
          :label="doctor.doctor_name"
        >
          <template #default="{ row }">
            <div class="schedule-cell">
              <template v-if="getDoctorSchedule(row.id, doctor.doctor_id)">
                <el-tag 
                  :type="getTimeSlotInfo(row.id, doctor.doctor_id)?.status === '已预约' ? 'danger' : 'success'"
                >
                  {{ getTimeSlotInfo(row.id, doctor.doctor_id)?.status || '可预约' }}
                </el-tag>
                <div v-if="getTimeSlotInfo(row.id, doctor.doctor_id)?.patient_name" class="patient-info">
                  患者：{{ getTimeSlotInfo(row.id, doctor.doctor_id).patient_name }}
                </div>
              </template>
              <el-tag v-else type="info">未排班</el-tag>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<style scoped>
.schedule-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-weight: 500;
}

.schedule-cell {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.patient-info {
  font-size: 12px;
  color: #666;
}
</style> 